package com.xyg.service.impl;

import com.xyg.dao.ProductRepository;
import com.xyg.pojo.Product;
import com.xyg.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public List< Product > findAll () {
        return productRepository.findAll();
    }

    @Override
    public Optional< Product > findById ( String id ) {
        return productRepository.findById( id );
    }

    @Override
    public Product save ( Product product ) {
        return productRepository.save( product );
    }

    @Override
    public Product updateById ( String id, Product productDetails ) {
        return productRepository.findById( id )
                .map( existingProduct -> {
                    if ( productDetails.getTitle() != null ) existingProduct.setTitle( productDetails.getTitle() );
                    if ( productDetails.getProcity() != null ) existingProduct.setProcity( productDetails.getProcity() );
                    if ( productDetails.getPrice() != null ) existingProduct.setPrice( productDetails.getPrice() );
                    if ( productDetails.getRealSales() != null ) existingProduct.setRealSales( productDetails.getRealSales() );
                    if ( productDetails.getPicPath() != null ) existingProduct.setPicPath( productDetails.getPicPath() );
                    return productRepository.save( existingProduct );
                } ).orElseThrow( () -> new RuntimeException( "未找到 ID 为: " + id + " 的产品" ) );
    }

    @Override
    public void deleteById ( String id ) {
        productRepository.deleteById( id );
    }
}
